import { useUserStore } from "@/stores/user";
import axios from "axios";
import { ElMessage } from "element-plus";
import "element-plus/theme-chalk/el-message.css";
import router from "@/router";
// 创建axios实例
const http = axios.create({
  baseURL: "http://localhost:8080",
  //timeout: 5000
});

// axios请求拦截器
http.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    const token = userStore.userInfo.token;
    if (token) config.headers.Authorization = `Bearer ${token}`;
    return config;
  },
  (e) => Promise.reject(e)
);

// axios响应式拦截器
http.interceptors.response.use(
  (response) => {
    const res = response.data;
    // 判断 code 是否为 1（成功状态）
    if (res.code === 1) {
      return res;
    } else {
      // 显示错误信息
      ElMessage({
        message: res.msg || "请求失败，请稍后重试",
        type: "error",
        duration: 3 * 1000,
      });
      return Promise.reject(new Error(res.msg || "请求失败，请稍后重试"));
    }
  },
  (e) => {
    const userStore = useUserStore();
    ElMessage.warning(e.response.data.message);
    if (e.response.status === 401) {
      userStore.clearUserInfo();
      router.push("/login");
    }
    return Promise.reject(e);
  }
);

export default http;
